import { Expandable } from '@/components';
import clsx from 'clsx';
import * as PropTypes from 'prop-types';
import React, { forwardRef } from 'react';
import Icon from '../Icon';
import styles from './index.less';

/** 表单段落布局 */
function FormSection(props, ref) {
  const { title, children, icon, right, className, expandable = false } = props;
  let $right = (
    <div className={styles.right}>
      {right}
      {expandable && (
        <span>
          &nbsp;&nbsp;
          <Expandable.Trigger />
        </span>
      )}
    </div>
  );
  let $title = (
    <div className={styles.header}>
      <h5 className={styles.title}>
        {icon !== null && <Icon type={icon ?? 'folder-add'} className={styles.icon} />}
        {title}
      </h5>
      {$right}
    </div>
  );

  if (expandable) {
    return (
      <Expandable defaultExpanded>
        <div ref={ref} className={clsx(styles.formSelection, className)}>
          {$title}
          <Expandable.Content>{children}</Expandable.Content>
        </div>
      </Expandable>
    );
  }

  return (
    <div ref={ref} className={clsx(styles.formSelection, className)}>
      {$title}
      {children}
    </div>
  );
}

export function CollapseFormSection(props) {
  const { right, children, ...rest } = props;
  return (
    <Expandable>
      <FormSection
        {...rest}
        right={
          <>
            {right}
            <Expandable.Trigger />
          </>
        }
      >
        <Expandable.Content>{children}</Expandable.Content>
      </FormSection>
    </Expandable>
  );
}

FormSection = forwardRef(FormSection);

FormSection.propTypes = {
  /** className */
  className: PropTypes.string,

  /** icon type */
  icon: PropTypes.string,

  /** 标题元素 */
  title: PropTypes.node,

  /** 标题行右边的元素 */
  right: PropTypes.node,

  expandable: PropTypes.bool,

  /** 内容/子元素 */
  children: PropTypes.node,
};

FormSection.Collapse = CollapseFormSection;

export default FormSection;
